<?php

namespace App\Http\Model;

/**
 * @package Service\Models
 * @property int $is_sale 是否上架(1是;2否)
 * @property int $status 状态(1正常;2删除)
 * @property int $is_check 是否通过审核(1是;2否)
 */
class Goods extends Base
{

    public $timestamps = false;

    /** @var int 上架 */
    const IS_ON_SALE = 1;
    /** @var int 下架 */
    const IS_OFF_SALE = 2;
    /** @var int 正常 */
    const STATUS_NORMAL = 1;
    /** @var int 删除 */
    const STATUS_DELETE = 2;
    /** @var int 审核 */
    const IS_CHECKED = 1;
    /** @var int 未审核 */
    const IS_UNCHECKED = 2;

    public static $tags = [
        1 => '特价',
        2 => '进口',
        4 => '新品',
    ];


    /**
     * 定义数据库表名
     *
     * @var string
     */
    protected $table = 'goods';

    /**
     * 定义主键名
     *
     * @var string
     */
    protected $primaryKey = 'goods_id';

    /**
     * The attributes that aren't mass assignable.
     *
     * @var array
     */
    protected $guarded = [];


    public function setCategory($category)
    {
        $this->category_id = $category->category_id;
        $this->category_tree = $category->getTree();

        return $this;
    }

    public function setCategoryFront($category)
    {
        $this->category_front_id = $category->category_front_id;
        $this->category_front_tree = $category->getTree();

        return $this;
    }

    public function setProvider($provider)
    {
        $this->provider_id = $provider->provider_id;

        return $this;
    }


    public function category()
    {
        return $this->belongsTo(Category::class, 'category_id', 'category_id');
    }

    public function categoryFront()
    {
        return $this->belongsTo(CategoryFront::class, 'category_front_id', 'category_front_id');
    }

    public function provider()
    {
        return $this->belongsTo(Provider::class, 'provider_id', 'provider_id');
    }


    public function skus()
    {
        return $this->hasMany(GoodsSku::class, 'goods_id', 'goods_id');
    }


    public function comments()
    {
        return $this->hasMany(GoodsComment::class, 'goods_id', 'goods_id');
    }

    public function goodsImgs()
    {
        return $this->hasMany(GoodsImg::class, 'goods_id', 'goods_id');
    }

    public function imgs()
    {
        return $this->belongsToMany(Img::class, 'goods_img', 'goods_id', 'img_id');
    }

    public function img()
    {
        return $this->hasOne(Img::class, 'id', 'img_id');
    }


    public function property()
    {
        return $this->hasMany(GoodsProperty::class, 'goods_id', 'goods_id');
    }

    public function getBaseProperties()
    {
        return Property::where('goods_id', '=', $this->goods_id)->andWhere('property_type', '=', '1')->get();
    }

    /**
     * 设置上下架
     *
     * @param $goods_id
     */
    public function setSale($goods_id)
    {
        $goods = Goods::where('goods_id', $goods_id)->first();
        if ($goods) {
            if ($goods->is_sale == 1) {
                $goods->is_sale = 2;
            } elseif ($goods->is_sale == 2) {
                $goods->is_sale = 1;
            }
            $goods->save();
        }
    }

    /**
     * 审核商品
     *
     * @param $param
     * @return array
     */
    public function verify($param)
    {
        //echo '<PRE>';print_r($param);exit;
        // 修改审核结果
        $goods = Goods::where('goods_id', $param['goods_id'])->first();
        if ($goods) {
            if ($param['is_check'] == 2 && empty(trim($param['remark']))) {
                return ['status' => 0, 'msg' => '请填写未通过原因'];
            }
            $goods->is_check = $param['is_check'];
            $goods->remark = $param['remark'];
            $goods->update_time = date('Y-m-d H:i:s');
            $goods->save();
        }
        // 修改积分
        if (isset($param['attr']) && count($param['attr'])) {
            // 有规格
            foreach ($param['attr'] as $key => $item) {
                if (intval($item['point']) > 0) {
                    $data['point'] = $item['point'];
                }
                if (intval($item['point_price']) > 0) {
                    $data['point_price'] = $item['point_price'];
                }
                if (isset($data)) {
                    GoodsSku::where('sku_id', $item['sku_id'])->update($data);
                }
            }
        } else {
            // 无规格
            if (intval($param['point']) > 0) {
                $data['point'] = $param['point'];
            }
            if (intval($param['point_price']) > 0) {
                $data['point_price'] = $param['point_price'];
            }
            if (isset($data)) {
                GoodsSku::where('goods_id', $param['goods_id'])->update($data);
            }

        }

        return ['status' => 1, 'msg' => '操作成功'];
    }

    /**
     * 商品列表
     *
     * @param array $conditions
     * @param int $paginate
     * @return mixed
     */
    public function goodslist($conditions = [], $paginate = 10)
    {
        $where = 'status = 1';
        if (isset($conditions['is_check']) && $conditions['is_check'] !== '') {
            $where .= ' and is_check = ' . $conditions['is_check'];
        }
        if (!empty($conditions['provider_id'])) {
            $where .= ' and provider_id = ' . $conditions['provider_id'];
        }
        if (!empty($conditions['is_sale'])) {
            $where .= ' and is_sale = ' . $conditions['is_sale'];
        }
        if (!empty($conditions['name'])) {
            $where .= " and name like '%" . $conditions['name'] . "%'";
        }
        if (!empty($conditions['goods_sn'])) {
            $sku = GoodsSku::whereRaw("goods_sn LIKE '%{$conditions['goods_sn']}%'")->get();
            if($sku->count()){
                $where .= " and goods_id IN(". implode(',',array_column($sku->toArray(),'goods_id')) .")";
            }
        }
        if(!empty($conditions['provider_name'])){
            $provider = Provider::whereRaw("name LIKE '%{$conditions['provider_name']}%'")->get();
            if($provider->count()){
                $where .= " and provider_id IN(". implode(',',array_column($provider->toArray(),'provider_id')) .")";
            }
        }
        if(!empty($conditions['time'])){
            $time_a = $conditions['time'].' 00:00:01';
            $time_b = $conditions['time'].' 23:59:59';
            $where .= " and update_time between '$time_a' and '$time_b'";
        }

        return Goods::whereRaw($where)->orderBy('goods_id', 'desc')->orderBy('update_time', 'desc')->paginate(
            $paginate
        )->appends($_GET);
    }

    /**
     * 修改商品
     *
     * @param $param
     * @return array
     */
    public function change($param)
    {

        $goods_id = $param['goods_id'];

        if (empty(trim($param['name']))) {
            return ['status' => 0, 'msg' => '请填写商品名称'];
        }

        if (empty($param['img_id']) || count($param['img_id']) == 0) {
            return ['status' => 0, 'msg' => '请上传商品图片'];
        }

        if (empty(trim($param['detail']))) {
            return ['status' => 0, 'msg' => '请填写商品详情'];
        }

        if (empty($param['category_front_id'])) {
            return ['status' => 0, 'msg' => '请选择前台分类'];
        }

        if (empty($param['default_img'])) {
            $default_img = $param['img_id'][0];
        } else {
            $default_img = $param['default_img'];
        }

        // 商品基本信息
        $date_time = date('Y-m-d H:i:s');
        $data = [
            'name'                => $param['name'],
            'describe'            => $param['describe'],
            'detail'              => $param['detail'],
            'category_id'         => $param['category_id'],
            'category_front_id'   => $param['category_front_id'],
            'category_tree'       => $this->getCategory($param['category_id'], 1),
            'category_front_tree' => $this->getCategory($param['category_front_id'], 2),
            'update_time'         => $date_time,
            'is_sale'             => $param['is_sale'],
            'is_check'            => 0,
            'minimum_purchase'    => $param['minimum_purchase'],
            'img_id'              => $default_img,
            'tags'                => isset($param['tags_value']) ? $param['tags_value'] : 0,
        ];

        $noSku = false;// 该商品有规格
        $goodsSku = GoodsSku::where('goods_id', $goods_id)->get();
        if ($goodsSku->count() == 1) {
            foreach ($goodsSku as $oneSku) {
                if (empty(trim($oneSku->sku_key))) {
                    $noSku = true;//该商品没有规格
                }
            }
        }

        //sku信息
        if (empty($param['attr']) || count($param['attr']) == 0) {
            if (floatval($param['price']) <= 0) {
                return ['status' => 0, 'msg' => '请填写商品零售价'];
            }

            if (floatval($param['market_price']) <= 0) {
                return ['status' => 0, 'msg' => '请填写商品市场价'];
            }

            if (floatval($param['purchase_price']) <= 0) {
                return ['status' => 0, 'msg' => '请填写商品采购价'];
            }

            //            if(intval($param['quantity']) <= 0){
            //                return ['status'=>0,'msg'=>'请填写商品库存'];
            //            }

            // 保存商品基本信息
            Goods::where('goods_id', $goods_id)->update($data);

            $data_sku = [
                'goods_id'       => $goods_id,
                'goods_sn'       => $param['goods_sn'],
                'goods_sn'       => $param['goods_sn'],
                //'sku_name' => $param['name'],
                'status'         => 1,
                'price'          => round(floatval($param['price']), 2),
                'market_price'   => round(floatval($param['market_price']), 2),
                'purchase_price' => round(floatval($param['purchase_price']), 2),
                'quantity'       => intval($param['quantity']),
                'update_time'    => $date_time,
                'is_default'     => 1,
            ];

            // 保存sku信息
            if ($noSku == false) {
                foreach ($goodsSku as $sku) {
                    $sku->delete();
                }
                GoodsSku::create($data_sku);
            } else {
                GoodsSku::where('goods_id', $goods_id)->update($data_sku);
            }

            GoodsProperty::where('goods_id', $goods_id)->delete();
            $this->addGoodsProperty($param, $goods_id);

            GoodsImg::where('goods_id', $goods_id)->delete();
            $this->addGoodsImg($param, $goods_id);

            return ['status' => 1, 'msg' => '修改成功'];

        } else {
            // 检查规格信息是否填写完全
            foreach ($param['attr'] as $key => $item) {
                if ($key == 'is_default') {
                    continue;
                }

                if (empty(trim($item['sku_name']))) {
                    return ['status' => 0, 'msg' => '请填写规格名称'];
                }

                if (floatval($item['price']) <= 0) {
                    return ['status' => 0, 'msg' => '请填写商品零售价'];
                }

                if (floatval($item['market_price']) <= 0) {
                    return ['status' => 0, 'msg' => '请填写商品市场价'];
                }

                if (floatval($item['purchase_price']) <= 0) {
                    return ['status' => 0, 'msg' => '请填写商品采购价'];
                }

                //                if(floatval($item['quantity']) <= 0){
                //                    return ['status'=>0,'msg'=>'请填写规格数量'];
                //                }
            }

            // 保存sku信息
            $is_default = isset($param['attr']['is_default']) ? $param['attr']['is_default'] : '';
            $num = 1;

            foreach ($param['attr'] as $key => $item) {
                if ($key == 'is_default') {
                    continue;
                }
                $data_sku = [
                    'goods_id'       => $goods_id,
                    'sku_key'        => $key,
                    'goods_sn'       => $item['goods_sn'],
                    'sku_name'       => $item['sku_name'],
                    'status'         => 1,
                    'price'          => round(floatval($item['price']), 2),
                    'market_price'   => round(floatval($item['market_price']), 2),
                    'purchase_price' => round(floatval($item['purchase_price']), 2),
                    'quantity'       => intval($item['quantity']),
                    'create_time'    => $date_time,
                ];

                //如果没有设置默认显示商品，则默认为第一条
                if (!$is_default && $num == 1) {
                    $data_sku['is_default'] = 1;
                } elseif ($is_default == $key) {
                    $data_sku['is_default'] = 1;
                }

                $add = true;//有没有需要新增的sku
                $change = false;//有没有需要修改的sku
                foreach ($goodsSku as $sku) {
                    if ($key == $sku->sku_key) {
                        $change = true;
                        $add = false;
                        break;
                    }

                }
                if ($add == true) {
                    GoodsSku::create($data_sku);
                }

                if ($change == true) {
                    GoodsSku::where('goods_id', $goods_id)->where('sku_key', $key)->update($data_sku);
                }
                $num++;

                //                echo '<PRE>';echo('add:'.$add);echo '<br/>';
                //                echo '<PRE>';print_r('change:'.$change);echo '<br/>';
            }


            foreach ($goodsSku as $sku) {
                $del = true;
                foreach ($param['attr'] as $key => $item) {
                    if ($sku->sku_key == $key) {
                        $del = false;
                        break;
                    }
                }
                if ($del == true) {
                    $sku->delete();
                }
                //echo '<PRE>';echo('del:'.$del);echo '<br/>';
            }
            //exit;
            GoodsProperty::where('goods_id', $goods_id)->delete();
            $this->addGoodsProperty($param, $goods_id);

            GoodsImg::where('goods_id', $goods_id)->delete();
            $this->addGoodsImg($param, $goods_id);

            return ['status' => 1, 'msg' => '修改商品成功'];
        }

    }

    /**
     * 添加商品
     *
     * @param $param
     * @return array
     */
    public function add($param)
    {

        //echo '<PRE>';print_r($param);exit;

        if ($param['goods_id']) {
            return $this->change($param);
        }

        if (empty(trim($param['name']))) {
            return ['status' => 0, 'msg' => '请填写商品名称'];
        }

        if (empty($param['img_id']) || count($param['img_id']) == 0) {
            return ['status' => 0, 'msg' => '请上传商品图片'];
        }

        if (empty(trim($param['detail']))) {
            return ['status' => 0, 'msg' => '请填写商品详情'];
        }

        if (empty($param['category_front_id'])) {
            return ['status' => 0, 'msg' => '请选择前台分类'];
        }

        if (empty($param['default_img'])) {
            $default_img = $param['img_id'][0];
        } else {
            $default_img = $param['default_img'];
        }

        // 商品基本信息
        $date_time = date('Y-m-d H:i:s');
        $data = [
            'name'                => $param['name'],
            'describe'            => $param['describe'],
            'detail'              => $param['detail'],
            'category_id'         => $param['category_id'],
            'category_front_id'   => $param['category_front_id'],
            'category_tree'       => $this->getCategory($param['category_id'], 1),
            'category_front_tree' => $this->getCategory($param['category_front_id'], 2),
            'create_time'         => $date_time,
            'update_time'         => $date_time,
            'is_sale'             => $param['is_sale'],
            'minimum_purchase'    => $param['minimum_purchase'],
            'is_check'            => 0,
            'img_id'              => $default_img,
            'tags'                => isset($param['tags_value']) ? $param['tags_value'] : 0,
        ];

        if ($param['provider_id']) {
            $data['provider_id'] = $param['provider_id'];
        }

        //sku信息
        if (empty($param['attr']) || count($param['attr']) == 0) {
            if (floatval($param['price']) <= 0) {
                return ['status' => 0, 'msg' => '请填写商品零售价'];
            }

            if (floatval($param['market_price']) <= 0) {
                return ['status' => 0, 'msg' => '请填写商品市场价'];
            }

            if (floatval($param['purchase_price']) <= 0) {
                return ['status' => 0, 'msg' => '请填写商品采购价'];
            }

            //            if(intval($param['quantity']) <= 0){
            //                return ['status'=>0,'msg'=>'请填写商品库存'];
            //            }

            // 保存商品基本信息
            $goods = Goods::create($data);
            $goods_id = (int)$goods->goods_id;
            if (!$goods_id) {
                return ['status' => 0, 'msg' => '添加商品基本信息失败'];
            }

            $data_sku = [
                'goods_id'       => $goods_id,
                'provider_id'    => $param['provider_id'],
                'goods_sn'       => $param['goods_sn'],
                //'sku_name' => $param['name'],
                'status'         => 1,
                'price'          => round(floatval($param['price']), 2),
                'market_price'   => round(floatval($param['market_price']), 2),
                'purchase_price' => round(floatval($param['purchase_price']), 2),
                'quantity'       => intval($param['quantity']),
                'create_time'    => $date_time,
                'is_default'     => 1,
            ];
            // 保存sku信息
            $goodsSku = GoodsSku::create($data_sku);
            if ($goodsSku->sku_id) {
                $this->addGoodsProperty($param, $goods_id);
                $this->addGoodsImg($param, $goods_id);

                return ['status' => 1, 'msg' => '添加商品成功'];
            } else {
                $goods->delete();

                return ['status' => 1, 'msg' => '添加商品规格信息失败'];
            }
        } else {
            // 检查规格信息是否填写完全
            foreach ($param['attr'] as $key => $item) {
                if ($key == 'is_default') {
                    continue;
                }

                if (empty(trim($item['sku_name']))) {
                    return ['status' => 0, 'msg' => '请填写规格名称'];
                }

                if (floatval($item['price']) <= 0) {
                    return ['status' => 0, 'msg' => '请填写商品零售价'];
                }

                if (floatval($item['market_price']) <= 0) {
                    return ['status' => 0, 'msg' => '请填写商品市场价'];
                }

                if (floatval($item['purchase_price']) <= 0) {
                    return ['status' => 0, 'msg' => '请填写商品采购价'];
                }

                //                if(floatval($item['quantity']) <= 0){
                //                    return ['status'=>0,'msg'=>'请填写规格数量'];
                //                }
            }

            // 保存商品基本信息
            $goods = Goods::create($data);
            $goods_id = (int)$goods->goods_id;
            if (!$goods_id) {
                return ['status' => 0, 'msg' => '添加商品基本信息失败'];
            }

            // 保存sku信息
            $is_default = isset($param['attr']['is_default']) ? $param['attr']['is_default'] : '';
            $num = 1;
            foreach ($param['attr'] as $key => $item) {
                if ($key == 'is_default') {
                    continue;
                }
                $data_sku = [
                    'goods_id'       => $goods_id,
                    'sku_key'        => $key,
                    'goods_sn'       => $item['goods_sn'],
                    'sku_name'       => $item['sku_name'],
                    'status'         => 1,
                    'price'          => round(floatval($item['price']), 2),
                    'market_price'   => round(floatval($item['market_price']), 2),
                    'purchase_price' => round(floatval($item['purchase_price']), 2),
                    'quantity'       => intval($item['quantity']),
                    'create_time'    => $date_time,
                ];

                //如果没有设置默认显示商品，则默认为第一条
                if (!$is_default && $num == 1) {
                    $data_sku['is_default'] = 1;
                } elseif ($is_default == $key) {
                    $data_sku['is_default'] = 1;
                }
                $goodsSku = GoodsSku::create($data_sku);
                if (!$goodsSku->sku_id) {
                    GoodsSku::where('goods_id', '=', $goods_id)->delete();
                    $goods->delete();

                    return ['status' => 1, 'msg' => '添加商品规格信息失败'];
                }
                $num++;
            }
            $this->addGoodsProperty($param, $goods_id);
            $this->addGoodsImg($param, $goods_id);

            return ['status' => 1, 'msg' => '添加商品成功'];
        }

    }

    public function addGoodsProperty($param, $goods_id)
    {
        if (isset($param['property2']) && count($param['property2'])) {
            foreach ($param['property2'] as $key => $item) {
                $property = Property::where('property_id', $key)->first();
                if ($property->value_type == 1 || $property->value_type == 2) {
                    if (!empty(trim($item))) {
                        $data = [
                            'property_type' => 1,
                            'goods_id'      => $goods_id,
                            'property_id'   => $key,
                            'property_name' => $property->name,
                            'value'         => $item,
                        ];
                        if ($property->value_type == 2) {
                            $propertyValue = PropertyValue::where('value_id', $item)->first();
                            $data['value'] = $propertyValue->name;
                            $data['value_id'] = $item;
                        }
                        GoodsProperty::create($data);
                    }
                }

                if ($property->value_type == 3) {
                    foreach ($item as $id) {
                        $propertyValue = PropertyValue::where('value_id', $id)->first();
                        $data = [
                            'property_type' => 1,
                            'goods_id'      => $goods_id,
                            'property_id'   => $key,
                            'property_name' => $property->name,
                            'value'         => $propertyValue->name,
                            'value_id'      => $id,
                        ];
                        GoodsProperty::create($data);
                    }
                }
            }
        }

        if (isset($param['property1']) && count($param['property1'])) {
            foreach ($param['property1'] as $key => $item) {
                $property = Property::where('property_id', $item)->first();
                if (!empty(trim($item))) {
                    $data = [
                        'property_type' => 2,
                        'goods_id'      => $goods_id,
                        'value_id'      => $item,
                        'property_name' => $property->name,
                    ];
                    GoodsProperty::create($data);
                }
            }
        }
    }

    public function addGoodsImg($param, $goods_id)
    {
        foreach ($param['img_id'] as $item) {
            GoodsImg::create(
                [
                    'goods_id'    => $goods_id,
                    'img_id'      => $item,
                    'create_time' => date('Y-m-d H:i:s'),
                ]
            );
        }
    }

    public function getGoodsInfo($goods_id)
    {

        $data['goods'] = [];
        $goods = Goods::where('goods_id', $goods_id)->first();
        if ($goods->count()) {
            $data['goods'] = $goods->toArray();
        }

        $data['goodsSku'] = [];
        $goodsSku = GoodsSku::where('goods_id', $goods_id)->get();
        if ($goodsSku->count()) {
            $data['goodsSku'] = $goodsSku->toArray();
        }

        $data['goodsNoSku'] = [];
        $goodsNoSku = GoodsSku::whereRaw('goods_id = ' . $goods_id . ' and sku_key is null')->first();
        if ($goodsNoSku) {
            $data['goodsNoSku'] = $goodsNoSku->toArray();
        }

        $data['goodsProperty'] = [];
        $goodsProperty = GoodsProperty::where('goods_id', $goods_id)->where('property_type', 1)->get();
        if ($goodsProperty->count()) {
            $data['goodsProperty'] = $goodsProperty->toArray();
        }

        $data['goodsImg'] = [];
        $goodsImg = GoodsImg::where('goods_id', $goods_id)->get();
        if ($goodsImg->count()) {
            $data['goodsImg'] = $goodsImg->toArray();
            foreach ($data['goodsImg'] as &$item) {
                $uploadFile = UploadFile::where('id', $item['img_id'])->first();
                if ($uploadFile) {
                    $item['path'] = $uploadFile->path;
                }
            }
        }

        $categoryFront = CategoryFront::where('category_front_id', $goods->category_front_id)->first();
        if ($categoryFront) {
            $data['goods']['categoryFront'] = $categoryFront->toArray();
        }

        //echo '<PRE>';print_r($data);exit;
        return $data;

    }

    public static function delById($goods_id)
    {
        Goods::where('goods_id', $goods_id)->update(['status' => 2]);
    }

    public static function getImgById($img_id)
    {
        return UploadFile::where('id', $img_id)->first();
    }

    public function getCategory($id, $type)
    {
        // 后台分类
        if ($type == 1) {
            $category = Category::where('category_id', $id)->first();
            $parent_tree = $category->parent_tree . ',' . $id;
        }
        if ($type == 2) {
            $category = CategoryFront::where('category_front_id', $id)->first();
            $parent_tree = $category->parent_tree . ',' . $id;
        }
        if ($parent_tree) {
            $parent_tree = explode(',', $parent_tree);
            if (!$parent_tree[0]) {
                unset($parent_tree[0]);
            }

            return implode(',', $parent_tree);
        }
    }


}
